#include "InSdkSoundPlay.h"
#include "InSdkSpkCtrl.h"

#define DEF_TAG         "AudioSound"

pthread_mutex_t g_InSdkSpkPlay_WavMutex;

Com_pvoid InSdkSpkPlay_WavThread(Com_pvoid path)
{
    pthread_mutex_lock(&g_InSdkSpkPlay_WavMutex);

    unsigned char buf[DEF_SDK_SPK_BUF_SIZE] = {0};
    Com_s32 size = 0;
    Com_s32 ret = -1;

    FILE *play_file = fopen(path, "rb");
    if(play_file == NULL)
    {
        PRT_ERR(DEF_TAG,"%s: fopen %s failed\n", __func__,(char *)path);
        goto exit;
    }

    Ext_InSdkSpkCtrl_CntAdd();
    usleep(300 * 1000);

    fseek(play_file, 44, SEEK_SET);
    while(1)
    {
        size = fread(buf, 1, DEF_SDK_SPK_BUF_SIZE, play_file);
        if(size >= DEF_SDK_SPK_BUF_SIZE)
        {
            ret = Ext_SdkSpk_Send_Buff(buf,size);
            if(ret != DEF_COM_SUCCESS)
            {
                break;
            }
        }
        else if (size == 0)
        {
            Ext_SdkSpk_Send_End_Buff();
            break;
        }
    }

    fclose(play_file);
exit:

    usleep(1500 * 1000);
    Ext_InSdkSpkCtrl_CntMinus();

    pthread_mutex_unlock(&g_InSdkSpkPlay_WavMutex);
    if(path != NULL)
    {
        free(path);
    }

    pthread_exit(NULL);
}

void Ext_InSdkSpkPlay_WavInit(char *path)
{
    char *wav_path;
    pthread_t id;

    wav_path = (char *)malloc(64);
    memset(wav_path,0,64);

    strcpy(wav_path,path);
    pthread_create(&id, NULL, InSdkSpkPlay_WavThread,wav_path);
    pthread_detach(id);
}

Com_void Ext_InSdkSpkPlay_LockInit(Com_void)
{
    pthread_mutex_init(&g_InSdkSpkPlay_WavMutex, NULL);
}

Com_void Ext_InSdkSpkPlay_LockDestroy(Com_void)
{
    pthread_mutex_destroy(&g_InSdkSpkPlay_WavMutex);
}
